package com.qf.leadnewswemediagateway.listeners;

import com.qf.qfleadnewsutils.commons.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(-5)
@Slf4j
public class LoginListener implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //登录或者注册相关的请求放行
        String uri = request.getURI().toString();
        log.info("请求uri:{}",uri);
        if (uri.contains("/login/in")){
            //放行
            return chain.filter(exchange);
        }

        //登录认证
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            //尝试从请求行中再获取一次
            token = request.getQueryParams().getFirst("token");
        }
        log.info("携带的token:{}",token);
        if (StringUtils.isEmpty(token)){
            //没有携带token信息，去登陆
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //有携带token -- 解析token
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int result = AppJwtUtil.verifyToken(claimsBody);

        if (result == 1 || result == 2){
            //token失效（过期或非法）
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //有效 针对游客模式判断是否是浏览咨询相关操作
        Long id = claimsBody.get("id", Long.class);
        log.info("当前登录的用户id:{}",id);


        //正常放行访问
        //为了避免后续的业务服务器再次解析token，这里我们将token中解析到的用户id作为头信息放行到后续业务服务器
        request = request.mutate().headers(httpHeaders -> {
            httpHeaders.set("uid", id + "");
        }).build();

        exchange = exchange.mutate().request(request).build();

        return chain.filter(exchange);
    }
}
